class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int n = nums.size();
        vector<int> f(n + 1, 1), g(n + 1, 1);
        int ret = INT_MIN;
        for(int i = 1; i <= n; i++) 
        {
            long long x = nums[i - 1], a = f[i - 1] * x, b = g[i - 1] * x;
            // 限制 a 和 b 在 int 范围内
            a = max((long long)INT_MIN, min(a, (long long)INT_MAX));
            b = max((long long)INT_MIN, min(b, (long long)INT_MAX));
            
            f[i] = max(x, max(a, b));
            g[i] = min(x, min(a, b));
            ret = max(f[i], ret);
        }
        return ret;


        // int n = nums.size();
        // vector<int> f(n + 1, 1), g(n + 1, 1);
        // int ret = INT_MIN;
        // for(int i = 1; i <= n; i++)
        // {
        //     long long x = nums[i - 1], a = (long long)f[i - 1] * x, b = (long long)g[i - 1] * x;
        //     f[i] = max({x, a, b});
        //     g[i] = min({x, a, b});
        //     ret = max(f[i], ret);
        // }
        // return ret;
    }
};